package com.yt.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * @Description:
 * @Author: mxli
 * @Date: 2021-01-12 21:13
 **/
@Slf4j
public class ImagesWmUtils {

    public static void doWm(File file){

        if(file != null){
            if(file.isDirectory()){
                File[] fs = file.listFiles();
                if(fs != null && fs.length > 0){
                    for(File f : fs){
                        if(f.isDirectory()){
                            doWm(f);
                        } else {
                            String filePath = f.getPath();
                            if(filePath.toLowerCase().contains(".png")
                                    || filePath.toLowerCase().contains(".jpg")
                                    || filePath.toLowerCase().contains(".jpeg")
                                    || filePath.toLowerCase().contains(".gif")){


                                try{
                                    String fileName = FileUtils.getFileName(filePath);
                                    String fileExtName =  FileUtils.getFileExtName(filePath);
                                    log.info("----" + fileName + "----"+ fileExtName);
                                    if(!fileName.toLowerCase().endsWith("wm")){
                                        Color color = Color.decode("#C2B7B6");
                                        markText(filePath, fileName+"wm."+fileExtName, "cqmall.com", "宋体", 1, 36, color, 0.3f, 0, fileExtName, 5, 0, 0);
                                    }
                                }catch (Exception e){
                                    log.error("-----------filePath:" + filePath);
                                }

//                                byte[] bytes =  MarkImageUtils.markText(FileUtils.inputStream2byte(f), "cqmall.com", "宋体", 1, 36, color, 0.3f, -45, "jpg", 5, 0, 0);
//                                ImageIO.write(ImageUtils.toImage(bytes), fileExtName, targerFile);
                            }
                        }
                    }
                }
            }
        }
    }

    public static void doWm(String path){
        File file = new File(path);
        doWm(file);
    }

    public static void main(String[] args) {
        String path = "/Users/mxli/Desktop/test_wm";
        doWm(path);
    }

    // 水印之间的间隔
    private static final int XMOVE = 200;
    // 水印之间的间隔
    private static final int YMOVE = 200;

    /**
     *
     * 文字水印
     * @param srcUrl 原图片路径，如：C://myPictrue//1.jpg
     * @param targerUrl 目标图片路径，如：C://myPictrue//1.jpg
     * @param pressText 水印文字， 如：云账房
     * @param fontName 体名称， 如：宋体
     * @param fontStyle 字体样式，如：粗体和斜体(Font.BOLD|Font.ITALIC)
     * @param fontSize 字体大小，单位为像素
     * @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明，1.0为完全不透明)
     * @param degree 水印图片旋转角度
     * @param location      水印位置：0、自定义 1、左上角，2、右上角，3、左下角，4、右下角，5、中间
     * @param x
     * @param y
     *
     */
    public static void markText(String srcUrl, String targerUrl, String pressText, String fontName, int fontStyle, int fontSize, Color color, float alpha, Integer degree, String fileExtName, Integer location, Integer x, Integer y) {

        try {
            File file = new File(srcUrl);
            BufferedImage targerImage = doMarkText(ImageUtils.toImage(file), pressText, fontName, fontStyle, fontSize, color, alpha, degree, location, x, y);
            File targerFile = new File(targerUrl);
            //注意这里的后缀不能带 .
            ImageIO.write(targerImage, fileExtName, targerFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理文字水印
     * @param srcImage
     * @param pressText
     * @param fontName
     * @param fontStyle
     * @param fontSize
     * @param color
     * @param alpha
     * @param degree
     * @param location
     * @param x
     * @param y
     * @return
     */
    public static BufferedImage doMarkText(BufferedImage srcImage, String pressText, String fontName, int fontStyle, int fontSize, Color color, float alpha, Integer degree, Integer location, Integer x, Integer y){

        int srcWidth = srcImage.getWidth();
        int srcHeight = srcImage.getHeight();

        BufferedImage targerImage = new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB);
        Font font = new Font(fontName, fontStyle, fontSize);
        Graphics2D g = targerImage.createGraphics();
        g.drawImage(srcImage,0, 0, srcWidth, srcHeight, null);
        g.setFont(font);
        g.setColor(color);

        if(!(alpha > 0 && alpha < 1)){
            if(alpha > 1 && alpha < 100){
                alpha = alpha /100;
            } else {
                alpha = 1;
            }
        }
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        if (null != degree) {
            // 设置水印旋转
//            degree = -45;
            g.rotate(Math.toRadians(degree), (double) targerImage.getWidth() / 2, (double) targerImage.getHeight() / 2);
        }

        //获取文字所占的像素
        FontRenderContext context = g.getFontRenderContext();
        Rectangle2D stringBounds = font.getStringBounds(pressText,context);

        int textWidth = (int) stringBounds.getWidth() ;
        int textHeight = (int) stringBounds.getHeight();

        x = -srcWidth / 2;
        y = -srcHeight / 2;
        int markWidth = fontSize * getTextLength (pressText);// 字体长度
        int markHeight = fontSize;// 字体高度

//        // 循环添加水印
//        while (x < srcWidth * 1.5) {
//            y = -srcHeight / 2;
//            while (y < srcHeight * 1.5) {
//                g.drawString (pressText, x, y);
//
//                y += markHeight + YMOVE;
//            }
//            x += markWidth + XMOVE;
//        }

        // 循环添加水印
//        y = - YMOVE;
//        while (y < srcHeight) {
//            x = -XMOVE;
//            while (x < srcWidth) {
//                g.drawString (pressText, x, y);
//
//                x += markWidth + XMOVE;
//            }
//            y += markHeight + YMOVE;
//        }


        // 横着水印
//        y = srcHeight / 2;
//        while (x < srcWidth * 1.5) {
//            x += markWidth + XMOVE;
//            g.drawString (pressText, x, y);
//        }

        // 竖着水印
        x = srcWidth / 2 - (markWidth / 2);
        y = 0;
        while (y < srcHeight) {
            y +=  markHeight + YMOVE;
            g.drawString (pressText, x, y);
        }

//        // 根据位置参数确定坐标位置
//        // location 位置： 1、左上角，2、右上角，3、左下角，4、右下角，5、中间
//        switch (location) {
//            case 0:
//                break;
//            case 1:
//                x = 0;
//                y = 0;
//                break;
//            case 2:
//                x = srcWidth - textWidth;
//                break;
//            case 3:
//                y = srcHeight - textHeight;
//                break;
//            case 4:
//                x = srcWidth - textWidth;
//                y = srcHeight - textHeight;
//                break;
//            case 5:
//                x = (srcWidth - textWidth) / 2;
//                y = (srcHeight - textHeight) / 2;
//                break;
//            default: break;
//        }

        g.drawString(pressText, x, y);
        g.dispose();

        return targerImage;
    }

    /**
     * 获取文本长度。汉字为1:1，英文和数字为2:1
     */
    private static int getTextLength (String text) {
        int length = text.length ();
        for (int i = 0; i < text.length (); i++) {
            String s = String.valueOf (text.charAt (i));
            if (s.getBytes ().length > 1) {
                length++;
            }
        }
        length = length % 2 == 0 ? length / 2 : length / 2 + 1;
        return length;
    }
}
